import 'package:floor/floor.dart';
import 'package:share_fit/app/helper/db/ute_database.dart';
import 'package:share_fit/app/tools/log_utils.dart';

class UteDbHelper {
  static UteDatabase? _database;
  static String? _name;

  UteDbHelper.init({String? dbName}) {
    _name = dbName ?? 'uteped_db.db';
    _dbInstance(_name!).then((value) {
      _database = value;
      logger.d('db name: $_name, instance: $_database');
    });
  }

  static Future<UteDatabase> getDB({String? dbName}) async {
    return _database ??= await _dbInstance(dbName ?? _name!);
  }

  Future<void> close() async {
    await _database?.close();
  }

  static Future<UteDatabase> _dbInstance(String dbName) {
    var db = $FloorUteDatabase.databaseBuilder(dbName).addCallback(_callback).build();
    logger.d('get new db instance: $db');
    return db;
  }

  /// 根据mac地址删除数据，如mac地址为空则删除所有数据
  static void cleanAllData({String? address}) {
    if (address != null && address.isNotEmpty) {
      clearAllDataWith(address);
    } else {
      clearAllData();
    }
  }

  static void clearAllDataWith(String address) {
    _database?.workoutDao.deleteAllByAddress(address);
    _database?.menstrualDao.deleteAllByAddress(address);
    _database?.sportsDao.deleteAllByAddress(address);
    _database?.sleepDao.deleteAllByAddress(address);
    _database?.stepDao.deleteAllByAddress(address);
    _database?.stressDao.deleteAllByAddress(address);
    _database?.spo2Dao.deleteAllByAddress(address);
    _database?.heartRateDao.deleteAllByAddress(address);
  }

  static void clearAllData() {
    _database?.workoutDao.deleteAll();
    _database?.menstrualDao.deleteAll();
    _database?.sportsDao.deleteAll();
    _database?.sleepDao.deleteAll();
    _database?.stepDao.deleteAll();
    _database?.stressDao.deleteAll();
    _database?.spo2Dao.deleteAll();
    _database?.heartRateDao.deleteAll();
  }

  static final _callback = Callback(
    onConfigure: (database) {
      logger.d('-----> onConfigure execute');
    },
    onCreate: (database, version) {
      /* 已创建数据库 */
      logger.d('-----> onCreate execute');
    },
    onOpen: (database) {
      /* 数据库已打开*/
      logger.d('-----> onOpen execute');
    },
    onUpgrade: (database, startVersion, endVersion) {
      /* 数据库已升级 */
      logger.d('-----> onUpgrade execute');
    },
  );
}
